package com.iyunwen.datatool.dataexport.impl;

import com.iyunwen.datatool.common.annotations.EventTypeAnnotation;
import com.iyunwen.datatool.common.enums.DataSourceTypeEnum;
import com.iyunwen.datatool.dataexport.DataExport;
import com.iyunwen.datatool.model.dbdo.EventDataDO;
import com.iyunwen.datatool.model.vo.DataGroupVO;
import com.iyunwen.datatool.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @description:
 * @author: Zhu.Guodong
 * @create: 2020-03-20 17:25
 * @version:
 */
@Slf4j
@Component
@EventTypeAnnotation(eventType = DataSourceTypeEnum.EVENT_LOG)
public class EventLogDataExport implements DataExport<DataGroupVO> {

    private String path;
    private List<String> cellHead;

    @Override
    public void initParams(String path, List<String> cellHead) {
        this.path = path;
        this.cellHead = cellHead;
    }


    @Override
    public void dataExportToFile(DataGroupVO data) {
        List<EventDataDO> eventData = data.getEventData();
        List<List<EventDataDO>> sourceEventData = data.getSourceEventData();
        String groupName = data.getGroupName() + "_事件数" + data.getEventData().size() + "_匹配数" + data.getSourceEventData().size();
        printExcel(eventData, sourceEventData, cellHead, path, groupName);
    }

    public static void printExcel(List<EventDataDO> tableDataList, List<List<EventDataDO>> sourceEventData, List<String> cellHead, String path, String groupName) {
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        // 写入数据到工作簿对象内
        Workbook workbook = ExcelUtils.exportData(tableDataList, sourceEventData, cellHead);

        // 以文件的形式输出工作簿对象
        FileOutputStream fileOut = null;
        try {
            String exportFilePath = path + groupName + ".xlsx";
            File exportFile = new File(exportFilePath);
            if (!exportFile.exists()) {
                exportFile.createNewFile();
            }

            fileOut = new FileOutputStream(exportFilePath);
            workbook.write(fileOut);
            fileOut.flush();
        } catch (Exception e) {
            log.error("输出Excel时发生错误，错误原因：" + e.getMessage());
        } finally {
            try {
                if (null != fileOut) {
                    fileOut.close();
                }
                if (null != workbook) {
                    workbook.close();
                }
            } catch (IOException e) {
                log.error("关闭输出流时发生错误，错误原因：" + e.getMessage());
            }
        }
    }
}
